#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QWindow>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_timer = new QTimer(this);          // 指定父对象，自动析构

    /* 2. 连接信号槽 */
    connect(m_timer, &QTimer::timeout, this, &MainWindow::onTimeout);

    /* 3. 启动：周期 50 ms，循环触发 */
    m_timer->start(50);

    connect(ui->pushButton,&QPushButton::clicked,this,&MainWindow::on_btn1_clicked);
    connect(ui->pushButton_2,&QPushButton::clicked,this,&MainWindow::on_btn2_clicked);
    ui->widget->setWindowFlags(Qt::FramelessWindowHint|ui->widget->windowFlags());
    ui->widget_2->setWindowFlags(Qt::FramelessWindowHint|ui->widget_2->windowFlags());
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_btn1_clicked(){
    HWND hB = reinterpret_cast<HWND>(ui->lineEdit->text().toULongLong());
    HWND hA = reinterpret_cast<HWND>(ui->widget->winId());
    wid1 = hB;
    refresh(hA,hB);
}

void MainWindow::on_btn2_clicked(){
    HWND hB = reinterpret_cast<HWND>(ui->lineEdit_2->text().toULongLong());
    HWND hA = reinterpret_cast<HWND>(ui->widget_2->winId());
    wid2 = hB;
    refresh(hA,hB);
}

void MainWindow::refresh(HWND hA,HWND hB){
    if (!IsWindow(hB) || !IsWindow(hA))
        return;

    // 1. 先挂父子关系
    SetParent(hB, hA);

    // 1. 彻底去边框
    LONG_PTR style = GetWindowLongPtr(hB, GWL_STYLE);
    style &= ~(WS_BORDER | WS_DLGFRAME | WS_THICKFRAME | WS_CAPTION);
    style |= WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
    SetWindowLongPtr(hB, GWL_STYLE, style);

    // 2. 把扩展边框也去干净
    LONG_PTR exStyle = GetWindowLongPtr(hB, GWL_EXSTYLE);
    exStyle &= ~(WS_EX_CLIENTEDGE | WS_EX_WINDOWEDGE | WS_EX_STATICEDGE);
    SetWindowLongPtr(hB, GWL_EXSTYLE, exStyle);
    int dx = GetSystemMetrics(SM_CXEDGE);
    int dy = GetSystemMetrics(SM_CYEDGE);
    // 3. 把窗口挪到父客户区左上角并填满
    RECT rc;
    GetClientRect(hA, &rc);
    SetWindowPos(hB, HWND_TOP,
                 -dx, -dy, rc.right+2*dx, rc.bottom+2*dy,
                 SWP_SHOWWINDOW | SWP_FRAMECHANGED);
}

void MainWindow::onTimeout()
{
    HWND hA1 = reinterpret_cast<HWND>(ui->widget->winId());
    HWND hA2 = reinterpret_cast<HWND>(ui->widget_2->winId());

    if(wid1!=0)
        refresh(hA1,wid1);
    if(wid2!=0)
        refresh(hA2,wid2);
}
